package th.retrofit.lib;

import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;

/**
 * https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
 * 给定 n 个非负整数，用来表示柱状图中各个柱子的高度。每个柱子彼此相邻，且宽度为 1 。
 * 求在该柱状图中，能够勾勒出来的矩形的最大面积。
 */
public class Solution84 {

    public int largestRectangleArea(int[] heights) {
        int hLen = heights.length;
        int[] left = new int[hLen];
        int[] right = new int[hLen];
        Arrays.fill(right, hLen);
        Deque<Integer> stack = new LinkedList<>();
        for (int i = 0; i < hLen; i++) {
            while (!stack.isEmpty() && heights[stack.peek()] >= heights[i]) {
                right[stack.peek()] = i;
                stack.pop();
            }
            left[i] = stack.isEmpty() ? -1 : stack.peek();
            stack.push(i);
        }
        int maxArea = 0;
        for (int i = 0; i < hLen; i++) {
            maxArea = Math.max(maxArea, (right[i] - left[i] - 1) * heights[i]);
        }
        return maxArea;
    }

    public static void main(String[] args) {
        int[] heights = new int[]{2, 1, 5, 6, 2, 3};
        System.out.println(new Solution84().largestRectangleArea(heights));
    }
}
